package com.hzchendou.blog.demo.resource.config;

import com.hzchendou.blog.demo.resource.security.filter.SecurityAuthTokenFilter;
import com.hzchendou.blog.demo.resource.security.handler.AuthAuthenticationEntryPoint;
import com.hzchendou.blog.demo.resource.security.handler.PathAccessDeniedHandler;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.context.SecurityContextPersistenceFilter;

/**
 * @Date: 2022-06-04 23:20
 * @since: 1.0
 */
@EnableWebSecurity
public class SpringSecurityWebConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {

        httpSecurity.formLogin().disable();
        httpSecurity.exceptionHandling()
                .accessDeniedHandler(new PathAccessDeniedHandler())
                .authenticationEntryPoint(new AuthAuthenticationEntryPoint());

        httpSecurity.authorizeRequests()
                .antMatchers("/admin/**").hasAuthority("admin")
                .antMatchers("/user/**").hasAuthority("user")
                .and().csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        httpSecurity.addFilterAfter(new SecurityAuthTokenFilter(), SecurityContextPersistenceFilter.class);
    }
}
